package com.example.studentvotesystem.controller;

import com.example.studentvotesystem.entity.ScenicSpot;
import com.example.studentvotesystem.service.ScenicSpotService;
import com.example.studentvotesystem.util.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
@RequestMapping("/spot")
public class ScenicSpotController {
    @Autowired
    private ScenicSpotService scenicSpotService;
    @Value("${file.upload-dir}")
    private String uploadDir;

    @GetMapping("/list")
    public String list(Model model) {
        model.addAttribute("spots", scenicSpotService.getAllSpots());
        return "spot/list";
    }

    @GetMapping("/add")
    public String addPage() {
        return "spot/add";
    }

    @PostMapping("/add")
    public String add(ScenicSpot scenicSpot, @RequestParam("image") MultipartFile image) throws IOException {
        if (!image.isEmpty()) {
            String imageUrl = FileUploadUtil.saveFile(image, uploadDir);
            scenicSpot.setImageUrl(imageUrl);
        }
        scenicSpotService.addSpot(scenicSpot);
        return "redirect:/spot/list";
    }

    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Integer id, Model model) {
        model.addAttribute("spot", scenicSpotService.getSpotById(id));
        return "spot/edit";
    }

    @PostMapping("/edit")
    public String edit(ScenicSpot scenicSpot, @RequestParam(value = "image", required = false) MultipartFile image) throws IOException {
        ScenicSpot existingSpot = scenicSpotService.getSpotById(scenicSpot.getId());

        if (image != null && !image.isEmpty()) {
            // 删除旧图片
            FileUploadUtil.deleteFile(existingSpot.getImageUrl(), uploadDir);
            // 保存新图片
            String imageUrl = FileUploadUtil.saveFile(image, uploadDir);
            scenicSpot.setImageUrl(imageUrl);
        } else {
            // 保留原有图片
            scenicSpot.setImageUrl(existingSpot.getImageUrl());
        }

        scenicSpotService.updateSpot(scenicSpot);
        return "redirect:/spot/list";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) throws IOException {
        ScenicSpot spot = scenicSpotService.getSpotById(id);
        // 删除关联的图片
        FileUploadUtil.deleteFile(spot.getImageUrl(), uploadDir);
        scenicSpotService.deleteSpot(id);
        return "redirect:/spot/list";
    }
}

